<?php

/**
 * 短信接口
 * @author jois
 */
class Sms
{

    // 多少时间内不能重复请求，180秒，即3分钟
    protected static $valid_time = 180;

    protected static $send_type = 'new92fox';

    // 发送通道：会员
    const CHANNEL_MEMBER = 'member';
    // 发送通道：行业
    const CHANNEL_INDUSTRY = 'industry';

    /**
     * 发送短消息
     *
     * @param type $mobile
     * @param type $content
     * @param type $sendType
     * @return type
     */
    public static function send($mobile, $content, $sendType = 'new92fox', $quickSend = FALSE)
    {
        $return = self::sendLimit();
        if (! $return['send'])
            return $return;

        $lvURL = "http://tool.92fox.com/index.php?r=sendmessage/SendMsg";
        $lvIP = self::getIP(); // IP
        $lvSource = self::getReferer(); // 来源
        $key = 'c=~98#4]a1746f)1,>ANER5Aa03c^?4f8(q0__]SXyR3^Au1HS82-?C|/\=8w4_:1V73e[=w^%zh?80BSA1b6/C9wfi0)x6f4r`1E9,t}6E1e4aFr6+35tb6]!96Au7q';
        $sig = md5($key . $mobile . $content); // 签名
        $lvSendChannel = self::CHANNEL_MEMBER; // 发送通道
        $lvChannel = empty($sendType) ? self::$send_type : $sendType; // 频道，统计分析用
        $lvData = "mobile={$mobile}&content={$content}&ip={$lvIP}&channel={$lvChannel}&sendchannel={$lvSendChannel}&source={$lvSource}&sig={$sig}";
        if ($quickSend)
            $lvData .= "&quicksend=pipaw20140918";
        $data = self::getURLContent($lvURL, $lvData);

        if (strpos($data, 'OK') !== FALSE)
            return array(
                "send" => TRUE,
                "info" => ""
            );
        else
            if (strpos($data, 'error'))
                return array(
                    "send" => FALSE,
                    "info" => "发送失败！"
                );
            else
                return array(
                    "send" => FALSE,
                    "info" => $data
                );
    }

    /**
     * 短信发送前的判断
     */
    protected static function sendLimit()
    {
        session_start();
        $time = time();

        // 上次引用来自baidu，直接拒绝
        if (strpos($_SERVER['HTTP_REFERER'], "baidu")) {
            return array(
                "send" => FALSE,
                "info" => "来自百度请求"
            );
        }
        // 3分钟内，只允许发送一次
        if (empty($_SESSION['lastSendTime']))
            $_SESSION['lastSendTime'] = $time;
        else {
            $time = $_SESSION['lastSendTime'];
            $nowTime = time();
            if ($nowTime - $time < self::$valid_time) {
                return array(
                    "send" => FALSE,
                    "info" => "3分钟内，请勿重复请求"
                );
            } else {
                $_SESSION['lastSendTime'] = $nowTime;
            }
        }

        // 同一个IP，只允许发送3次(可以是3个不同的手机号码)
        if (empty($_SESSION['count']))
            $_SESSION['count'] = 1;
        else {
            $count = $_SESSION['count'];

            if ($count > 3) {
                return array(
                    "send" => FALSE,
                    "info" => "请求次数超出范围"
                );
            } else {
                $count ++;
                $_SESSION['count'] = $count;
            }
        }

        return array(
            "send" => true,
            "info" => "正常请求"
        );
    }

    /**
     * 取得IP地址
     *
     * @global type $ip
     * @return string
     */
    protected static function getIP()
    {
        $clientip = '';
        if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $clientip = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $clientip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $clientip = getenv('REMOTE_ADDR');
        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $clientip = $_SERVER['REMOTE_ADDR'];
        }

        preg_match('/[\d\.]{7,15}/', $clientip, $clientipmatches);
        $clientip = $clientipmatches[0] ? $clientipmatches[0] : 'unknown';
        return $clientip;
    }

    /**
     * 取得请求来源地址
     */
    private static function getReferer()
    {
        return $_SERVER['HTTP_REFERER'];
    }

    /**
     * 取得URL内容
     *
     * @param unknown $pURL
     * @param string $pPostData
     * @return mixed
     */
    public static function getURLContent($pURL, $postData = '')
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $pURL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1); // 连接超时（秒）
        curl_setopt($ch, CURLOPT_TIMEOUT, 3); // 执行超时（秒）

        if ($postData) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        }

        $out_put = curl_exec($ch);
        curl_close($ch);

        return $out_put;
    }
}